 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 class timeline extends CI_Controller {
 	var $data;
 	public function __construct()
 	{
 		parent::__construct();

 		$this->load->library('session');
 		$this->load->library('pagination');
 		$this->load->library('fclass');
 		$data['title'] = "TIMELINE";
 		$this->load->model('model_feeds');
 		$this->load->model('model_customer');
 		$this->load->model('model_user');
		// CHECK LOGIN
 		$check = $this->session->userdata('login');
 		if($check==false){
 			redirect(base_url().'login/', 'refresh');
 			return;
 		}
 	}

 	public function index()
 	{
 		$this->view();
		
		//$this->load->view('customer', $this->data);
 	}

 	public function view($paging=0){
		$user_info = $this->session->userdata('user_info');
	//print_r($this->session->userdata('user_info'));
 		if($paging<0){
 			$paging=0;
 		}
 		$this->data["result"] = $this->model_feeds->select(array('feed_creator_id'=>$user_info["user_id"],"limit"=>10,"paging"=>$paging));
 		$this->data["count_page"] = $this->model_feeds->selectCount(array('feed_creator_id'=>$user_info["user_id"]));
 		if(isset($_REQUEST["cust_id"])&&$_REQUEST["cust_id"]!=""){ 
 			$this->data["result_cust"] = $this->model_customer->selectDetail(array("cust_creator_id"=>$user_info["user_id"],"cust_id"=>$_REQUEST["cust_id"]));

 			if(count($this->data["result_cust"])<1){
 				exit();
 			}

 		}
 		$this->data["set_page"] 	= 'timeline_list';
        
 		$this->load->view('qt/timeline', $this->data);

 	}
 	public function add_feeds(){
		$user_info = $this->session->userdata('user_info');
		$token =  $this->session->userdata('user_token');
 		session_start();
 		$content = @$_REQUEST["content"];
 		$cust_id = @$_REQUEST["cust_id"];
 		$day	 = @$_REQUEST["day"];
 		$time 	 = @$_REQUEST["time"];
 		$type 	 = @$_REQUEST["type"];
 		$status = 0;

 		$s=explode('/', $day );
 		$date = @strtotime($s[1].'/'.$s[0].'/'.$s[2].' '.$time);

//echo json_encode(array("result"=>$status,"url"=>'http://lms.altamedia.vn/supersale/?page=add&content='.urlencode($content).'&cus_id='.urlencode($cust_id).'&cus_name='.urlencode($row["cust_first_name"]." ".$row["cust_last_name"]).'&id_comp='.urlencode($row["comp_id"]).'&name_comp='.urlencode($row["comp_name"]).'&check_conflict='.$check_conflict.'&url=http://crm.altamedia.vn/timeline'));
//return;
 		$result_cust =$this->model_customer->selectIdDetail(array('cust_id'=>$cust_id,"join_companies"=>""));
		//print_r($result_cust);
		//print_r($result);
 		if($type==3){
			$_refix = "LED"; // mỗi sản phẩm kiểm tra chỉ cần thay đổi giá trị này
			/*
			// TẠO HỢP ĐỒNG LED

			// Kiểm tra conflict
			$row=$result;
			$check_conflict = false;
			$saleResult = $this->model_customer->checkExistsJoin(array('cust_phone'=>$row["cust_phone"],'cust_email'=>$row["cust_email"],'cust_cmnd'=>$row["cust_cmnd"],'cust_tax_code'=>$row["cust_tax_code"]));
			$my_permisstion =  $this->session->userdata('permission_apps');
		//	print_r($my_permisstion);
			//print_r($saleResult);
			foreach($saleResult as $val ){
				$rs = $this->model_user->selectPermitionApp(array("app_id"=>2,"user_id"=>$val["uId"]));
				//print_r($rs);
				//echo $val["uId"];
				if(count($rs)>0){
					$permissions = json_decode($rs["permissions"]);
					foreach($permissions->business as $k => $vl){
						foreach($my_permisstion["business"]  as $ke => $value){
							if($k == $ke&&$value=="on"&&$vl=="on"&&strtoupper($ke)=="LED"){
								//if($row["cust_conflict_id"]!=""){									
									$check_conflict = true;
								//}
							}
						}
					}
				}
				
			}
			*/
			//echo "sdad";
			//$array = array("LED","TEST");
			//echo json_encode($array);
			$check_conflict = false;
			$my_manager = false;
			$my_permisstion =  $this->session->userdata('permission_apps');
			$line_prefix =array();
			$result = $this->model_customer->selectListConflict(array('cust_id'=>$cust_id));
			//print_r($result );
			//echo "1";
			foreach ($result as $key => $value) {
				$row = $value;
				$line_prefix = json_decode($value["line_prefix"],true);	
				
				if($value["uId"]==$user_info["user_id"]&&count($line_prefix)>0&&in_array($_refix, $line_prefix)==true){
					$my_manager = true;
				}
					

				//print_r($line_prefix);
				if(count($line_prefix)>0&&in_array($_refix, $line_prefix)==true){ // User QUản lý Khách hàng này đã tồn tại quản lý LED
					echo "3";
					// Trả ra user nào đang quản lý khách hàng này
					//$id_user = $value["uId"];
				//	if($id_user == $this->session->userdata('uId')){ // Chính sale khởi tạo là người  quản lý user này luôn
						// Không xảy ra xung đột
					//}else{ // Sale này không quản lý nên xảy ra conflict
					$saleResult = $this->model_customer->checkExistsJoinData(array('cust_phone'=>$row["cust_phone"],'cust_email'=>$row["cust_email"],'cust_cmnd'=>$row["cust_cmnd"],'cust_tax_code'=>$row["cust_tax_code"]));
					//echo $this->db->last_query();
					
					$result_user = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&app_name=AM_SALE_SUPPORT");
					$json = json_decode($result_user,true);
					if(count($saleResult)>1){
						foreach($saleResult as $val ){
							foreach($json["users"] as $k => $vl){
								if($vl["user_id"]!=$user_info["user_id"]){
							
									if(count($vl["user_line"])>0&&in_array($vl["user_line"],strtolower($_refix))){
										$check_conflict = true;
									}
								}
							}
							
						// Lấy quyền tung user hoat dong tren nganh hang
						// Dùng API danh sách thành viên kiểm tra với user hiện tại có thằng nào có quyền giống user hiện tại không, nếu có sẽ conflig
						/*
						$rs = $this->model_user->selectPermitionApp(array("app_id"=>2,"user_id"=>$val["uId"]));	
							if(count($rs)>0){
								$permissions = json_decode($rs["permissions"],true);
								foreach($permissions["business"] as $k => $vl){
									foreach($my_permisstion["business"]  as $ke => $value){
										if($k == $ke&&$value=="on"&&$vl=="on"&&strtoupper($ke)==$_refix){
											$check_conflict = true;
										}
									}
								}
							}
							*/
						}
					
					}
				//echo "test 2";

				//	}
		
				}else{ // Không có user nào quản lý led trong bảng nên xảy ra conflict		

					//echo "test 1";
			
					$saleResult = $this->model_customer->checkExistsJoinData(array('cust_phone'=>$row["cust_phone"],'cust_email'=>$row["cust_email"],'cust_cmnd'=>$row["cust_cmnd"],'cust_tax_code'=>$row["cust_tax_code"]));
					//echo $this->db->last_query();
					//print_r($saleResult);
					//echo $this->db->last_query();
					//print_r($saleResult);
					if(count($saleResult)>1){
						$check_conflict = true;
					}
					
				}
		
			}
	//	exit();
//echo "sdasd";
//echo "test".$check_conflict;

			if($my_manager==true){
				$check_conflict = false;
			}

			$row = $result_cust;
			echo json_encode(array("result"=>$status,"url"=>'http://lms.altamedia.vn/supersale/?token='.$this->session->userdata('user_token').'&page=add&content='.urlencode($content).'&cus_id='.urlencode($cust_id).'&cus_name='.urlencode($row["cust_first_name"]." ".$row["cust_last_name"]).'&id_comp='.urlencode($row["comp_id"]).'&name_comp='.urlencode($row["comp_name"]).'&check_conflict='.$check_conflict.'&url=http://crm.altamedia.vn/timeline'));
			exit();
		}else if($type==4){
			// TẠO DỰ ÁN
		//	echo  json_encode(array("result"=>$status,"url"=>'http://bms.altamedia.vn/?parameter[cust_id]='.$cust_id.'&parameter[project_dead]='.$day.'&parameter[creater_id]='.$this->session->userdata('uId').'#project_create'));
				//$data = $this->load->view('qt/project_form', $this->data);
				//echo  json_encode(array("result"=>7,"data"=>$data));
			
			$projectContent = $this->input->get_post("projectContent");
			$cust_id = $this->input->get_post("cust_id");
			$projectStart = $this->input->get_post("projectStart");
			$projectDead = $this->input->get_post("projectDead");
			$groupMember = $this->input->get_post("groupMember");
			$projectName = $this->input->get_post("projectName");
			
			$group_us = "";
			if($groupMember!=""&&count($groupMember)>0){
				foreach($groupMember as $val){
					$group_us ="&member[]=".$val.$group_us;
				}
			}
			//echo "http://localhost/ht/bms_alta_media/api/project_create/?token=".$token."&title=".urlencode("[SALES SUPPORT]".$projectName)."&content=".urlencode($projectContent)."&start_date=".urlencode($projectStart)."&end_date=".urlencode($projectDead)."&leader=".$user_info["user_id"]."&contract=&credit=".$group_us;
			$result= file_get_contents("http://localhost/ht/bms_alta_media/api/project_create/?token=".$token."&title=".urlencode("[SALES SUPPORT]".$projectName)."&content=".urlencode($projectContent)."&start_date=".urlencode($projectStart)."&end_date=".urlencode($projectDead)."&leader=".$user_info["user_id"]."&contract=&credit=".$group_us);
			$json = json_decode($result,true);
			if($json["result"]==false){
				echo  json_encode(array("result"=>0,"msg"=>$json["msg"]));
				exit();
			}else{
				$content ="Tạo Dự Án Thành Công <br/>Mã Dự Án:".$json["project_code"]." <br/>Tên Dự Án:"."[SALES SUPPORT]".$projectName." <br/> Nội Dung:".$projectContent." <br/> Ngày Bắt Đầu:".$projectStart." <br/> Ngày Kết Thúc:".$projectDead;
				
				$s=explode('-', $projectStart);
				$date = @strtotime($s[1].'/'.$s[0].'/'.$s[2].' '.$time);
			}
		
		}


		if(trim($content)==""){
			$status= -1;
		}else if(trim($cust_id)==""){
			$status= -2;
		//}else if(trim($day)==""){
		//	$status =-3;
		}else{
			$this->model_feeds->insert(array('feed_content'=>$content,'feed_creator_id'=>$user_info["user_id"],"feed_cust_id"=>$cust_id,"feed_action_time"=>$date,"feed_create_time"=>time()));

			$status = 1;
		}

		if($type==2){
			// INSERT CÔNG VIỆC MỚI TRÊN SYSTEM TẠI ĐÂY
			$row=$result_cust;
			// Lấy nội dung 160 ký tự làm tiêu đề (title).
			
			$result= file_get_contents("http://localhost/ht/bms_alta_media/api/task_create/?token=".$token."&title=".urlencode("[SALES SUPPORT]".$this->fclass->subStringVN($content,160))."&content=".urlencode($content." với ".$row["cust_name"])."&start_date=".urlencode(date('d-m-Y',time()))."&end_date=".urlencode(date('d-m-Y',$date)));
			$vals=json_decode($result);
			
		
		}
		
	//print_r($user_info);
	
		echo  json_encode(array("result"=>$status,"username"=>$user_info["full_name"],"content"=>$content,"time"=>date('d/m/Y H:i:s',$date)));

	}
	
	public function load_project_form(){
		$this->data["user"]  = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&app_name=AM_SALE_SUPPORT");
		
		$this->data["result"] = array("content"=>$this->input->get_post("content"),"cust_id"=>$this->input->get_post("cust_id"),"day"=>$this->input->get_post("day"));
		$data = $this->load->view('qt/project_form', $this->data);
	}
}
?>